package jp.tkym.labs.gwt.client.table;

import java.util.List;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class FlexTableBinder {
	private FlexTable table;
	private FlexTableBindModel model;
	private int rowStart;
	private int colStart;
	
	public FlexTableBinder(FlexTable table, FlexTableBindModel model, int row, int col){
		this.table = table;
		this.model = model;
		this.rowStart = row;
		this.colStart = col;
	}
	
	public FlexTableBinder(FlexTable table, FlexTableBindModel model){
		this(table, model, 0, 0);
	}
	
	public void bind(){
		model.ensureSpan();
		model.fill();
		List<List<FlexTableBindSource>> rows = model.sources();
		int trow = rowStart; 
		for(int row=0; row<rows.size(); row++){
			List<FlexTableBindSource> columns = rows.get(row);
			int tcol = colStart;
			for(int col=0; col<columns.size(); col++){
				if(!model.isInvalid(row, col)){
					FlexTableBindSource element = columns.get(col);
					bindElement(table, trow, tcol, element);
					tcol++;
				}
			}
			trow++;
		}
	}
	
	private void bindElement(FlexTable table, int row, int col, FlexTableBindSource element){
		int colspan = element.getColspan();
		int rowspan = element.getRowspan();
		table.getFlexCellFormatter().setColSpan(row, col, colspan);
		table.getFlexCellFormatter().setRowSpan(row, col, rowspan);
		
		String stylename = element.getStyleName();
		if(stylename != null && stylename != "") 
			table.getFlexCellFormatter().setStyleName(row, col, stylename);
		
		Widget widget = element.getWidget();
		table.setWidget(row, col, widget);
	}
}